import { MAPCONFIG } from '../../config/config';
import { genDefDate } from '../../utils/DateUtils';
import { genCloudFilePath } from '../../utils/CloudUtils';
const app = getApp();
const chooseLocationPlugin = requirePlugin('chooseLocation');
const MAPKEY = MAPCONFIG.MAPKEY;
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    index: null,
    isShowAuth: false,
    petName:'',
    petType:'',
    startDate: genDefDate(),
    endDate: genDefDate(),
    location:{},
    paid:false,
    money:0,
    imgList: [],
    content: ''
  },
  onShow() {
    const location = chooseLocationPlugin.getLocation();
    if (location) {
      console.log(location);
      this.setData({ location: location });
    }else{
      this.checkLogin();
    }

  },
  bindKeyInput(e){
    const key = e.currentTarget.dataset.key;
    let data={};
    data[key] = e.detail.value;
    this.setData(data);
  },
  startDateChange(e) {
    this.setData({
      startDate: e.detail.value
    })
  },
  endDateChange(e) {
    this.setData({
      endDate: e.detail.value
    })
  },
  paidChange(e){
    if (e.detail.value){
      this.setData({
        paid: e.detail.value
      })
    }else{
      this.setData({
        paid: e.detail.value,
        money:0
      })
    }
  },
  chooseLocation(e) {
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${MAPKEY}&referer=留守宠物`
    });
  },
  ChooseImage() {
    const count = 3 - this.data.imgList.length;//最多3张图片
    if (count < 1) {
      return;
    }
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '操作确认',
      content: '确定要删除这张照片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  uploadImg(filePath) { // 调用wx.cloud.uploadFile上传文件
    return wx.cloud.uploadFile({
      cloudPath: genCloudFilePath(filePath),
      filePath: filePath
    })
  },
  saveData(data){
    wx.showLoading({ title: '发布中' });
    const uploadTasks = data.imgList.map(item => this.uploadImg(item))
    Promise.all(uploadTasks).then(result => {
      console.log(result);
      const imgList = result.map(img => (img.fileID));
      data.imgList = imgList;
      console.log(data);
      const db = wx.cloud.database();
      data.geo = db.Geo.Point(data.location.longitude, data.location.latitude);
      db.collection('pet').add({
        data: data
      }).then(result => {
        console.log('保存成功', result)
        wx.hideLoading()
        wx.showToast({ title: '发布成功审核中', duration: 2000})
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/record/record',
          }) }, 2000);
        }).catch(() => {
          wx.hideLoading()
          wx.showToast({ title: '发布失败', icon: 'error' })
        })
      
    }).catch(() => {
      wx.hideLoading()
      wx.showToast({ title: '上传图片错误', icon: 'error' })
    })
  },
  tapPublish(){
    console.log("tapPublish");
    if(this.checkLogin()==false){
      return;
    }
    let data = {};
    let errorMsg = "";
    data.petName = this.data.petName;
    data.petType = this.data.petType;
    data.paid    = this.data.paid;
    data.money   = this.data.money;
    data.content = this.data.content;
    data.startDate = this.data.startDate;
    data.endDate = this.data.endDate;
    data.imgList = this.data.imgList;
    data.location = this.data.location;
    data.deleteTime = '';
    data.publishTime = '';
    data.published  = false;//待审核
    data.createTime = new Date().getTime();
    
    if (data.paid && data.money==0){
      errorMsg = '有偿服务报酬不能为0';
    }
    if (typeof(data.location.name) =='undefined') {
      errorMsg = '请选择地址';
    }
    if (data.imgList.length < 1) {
      errorMsg = '至少上传一张照片';
    }
    if (data.petName == "" || data.petType == "") {
      errorMsg = '请完善宠物信息';
    }
    if (errorMsg){
      wx.showToast({
        title: errorMsg,
        icon: 'none'
      })
      return;
    }

    this.saveData(data);
  },
  checkLogin(){
    let userInfo = app.globalData.userInfo || {};
    if (!userInfo.mobile) {
      wx.showToast({
        icon: 'none',
        title: '请先登录帐号',
        duration: 1000,
      })
      this.showAuthDialog();
      return false;
    }else{
      return true;
    }
  },
  showAuthDialog() {
    this.setData({
      isShowAuth: true
    })
  },
  onAuthEvent: function (e) {
    console.log('onAuthEvent', e);
  }
})